// Copyright 2024 Tvux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package _209

// minSubArrayLen
// 注意：子数组必须是连续的才叫子数组，而不是数组中某几个元素所构成的数组就叫子数组
// 所以可以想到滑动窗口的解法
func minSubArrayLen(target int, nums []int) int {
	left := 0               // 记录窗口的左边界
	sum := 0                // 记录当前窗口内元素的和
	minLen := len(nums) + 1 // 记录最小的子数组长度
	for right, v := range nums {
		// 先将当前元素加入窗口
		sum += v
		for sum >= target {
			// 如果当前窗口内的元素和大于等于目标值，就更新最小子数组长度
			if right-left+1 < minLen {
				minLen = right - left + 1
			}
			// 然后将窗口的左边界向右移动，缩小窗口
			sum -= nums[left]
			left++
		}
	}
	// 如果最小子数组长度没有被更新过，说明不存在符合条件的子数组，返回0
	if minLen == len(nums)+1 {
		return 0
	}
	return minLen
}
